package com.jack.leetcode.eachproblem_2020;

/**
 * Created by zhang_j on 2020/10/29
 */
public class 求根到叶子节点数字之和 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public static int sumNumbers(TreeNode root) {
        if(root == null){
            return 0;
        }
        return countNumber(root, 0);
    }

    private static int countNumber(TreeNode root, int count){
        int sum = 0;
        if(root == null){
            return 0;
        }
        int tmp = count * 10 + root.val;
        if(root.left == null && root.right == null){
            return tmp;
        }
        if(root.left != null){
            sum += countNumber(root.left, tmp);
        }
        if(root.right != null){
            sum += countNumber(root.right, tmp);
        }
        return sum;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(9);
        root.left.left = new TreeNode(5);
        root.left.right = new TreeNode(1);
        root.right = new TreeNode(0);
        System.out.println(sumNumbers(root));

        TreeNode a = new TreeNode(1);
        a.left = new TreeNode(2);
        a.right = new TreeNode(3);
        System.out.println(sumNumbers(a));
    }
}
